import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  Modal, 
  Form, 
  InputNumber, 
  message, 
  Popconfirm, 
  Tag, 
  Space,
  Card,
  Typography,
  Tooltip,
  Select,
  Row,
  Col,
  Pagination
} from 'antd';
import { 
  PlusOutlined, 
  DeleteOutlined, 
  CopyOutlined,
  ReloadOutlined,
  DownloadOutlined
} from '@ant-design/icons';
import { accountService } from '@/services/accountService';
import { InvitationCode } from '@/types/account';

const { Title } = Typography;

// 简单的日期格式化函数
const formatDateTime = (dateStr: string) => {
  return new Date(dateStr).toLocaleString('zh-CN');
};

const InvitationCodeManagement: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [invitationCodes, setInvitationCodes] = useState<InvitationCode[]>([]);
  const [filteredInvitationCodes, setFilteredInvitationCodes] = useState<InvitationCode[]>([]);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [exportLoading, setExportLoading] = useState(false);
  const [usageFilter, setUsageFilter] = useState<'all' | 'used' | 'unused'>('all');
  const [form] = Form.useForm();
  
  // 分页状态
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
    totalPages: 0,
  });

  // 加载邀请码列表
  const loadInvitationCodes = async (page = 1) => {
    setLoading(true);
    try {
      const response = await accountService.getInvitationCodes(page);
      const data = response.data;
      
      setInvitationCodes(data.results);
      setPagination({
        current: data.current_page,
        pageSize: data.page_size,
        total: data.count,
        totalPages: data.total_pages,
      });
      
      // 应用筛选到当前页数据
      applyFilter(data.results, usageFilter);
    } catch (error: any) {
      message.error(error.response?.data?.message || '获取邀请码列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 应用筛选
  const applyFilter = (codes: InvitationCode[], filter: 'all' | 'used' | 'unused') => {
    let filtered = codes;
    switch (filter) {
      case 'used':
        filtered = codes.filter(code => code.is_used);
        break;
      case 'unused':
        filtered = codes.filter(code => !code.is_used);
        break;
      case 'all':
      default:
        filtered = codes;
        break;
    }
    setFilteredInvitationCodes(filtered);
  };

  // 处理筛选变化
  const handleFilterChange = (value: 'all' | 'used' | 'unused') => {
    setUsageFilter(value);
    applyFilter(invitationCodes, value);
  };

  useEffect(() => {
    loadInvitationCodes();
  }, []);

  // 当筛选条件变化时，重新应用筛选
  useEffect(() => {
    applyFilter(invitationCodes, usageFilter);
  }, [usageFilter, invitationCodes]);

  // 处理分页变化
  const handlePageChange = (page: number) => {
    loadInvitationCodes(page);
  };

  // 生成邀请码
  const handleCreateInvitationCodes = async (values: { count: number }) => {
    try {
      const response = await accountService.createInvitationCodes(values);
      message.success(`成功生成 ${response.data.length} 个邀请码`);
      setCreateModalVisible(false);
      form.resetFields();
      loadInvitationCodes();
    } catch (error: any) {
      message.error(error.response?.data?.message || '生成邀请码失败');
    }
  };

  // 删除邀请码
  const handleDeleteInvitationCode = async (codeId: number) => {
    try {
      await accountService.deleteInvitationCode(codeId);
      message.success('邀请码已删除');
      loadInvitationCodes();
    } catch (error: any) {
      message.error('删除邀请码失败');
    }
  };

  // 复制邀请码到剪贴板
  const handleCopyCode = async (code: string) => {
    try {
      await navigator.clipboard.writeText(code);
      message.success('邀请码已复制到剪贴板');
    } catch (error) {
      message.error('复制失败');
    }
  };

  // 导出邀请码到Excel
  const handleExportInvitationCodes = async () => {
    setExportLoading(true);
    try {
      const blob = await accountService.exportInvitationCodes();
      
      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      
      // 生成文件名：邀请码列表_YYYYMMDD_HHMMSS.xlsx
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      
      const fileName = `邀请码列表_${year}${month}${day}_${hours}${minutes}${seconds}.xlsx`;
      link.download = fileName;
      
      // 触发下载
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      // 清理URL对象
      window.URL.revokeObjectURL(url);
      
      message.success('邀请码列表导出成功');
    } catch (error: any) {
      message.error(error.response?.data?.message || '导出失败');
    } finally {
      setExportLoading(false);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '邀请码',
      dataIndex: 'code',
      key: 'code',
      render: (code: string) => (
        <Space>
          <code style={{ fontFamily: 'monospace', fontSize: '12px' }}>{code}</code>
          <Tooltip title="复制邀请码">
            <Button 
              type="text" 
              size="small" 
              icon={<CopyOutlined />} 
              onClick={() => handleCopyCode(code)}
            />
          </Tooltip>
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'is_used',
      key: 'is_used',
      width: 100,
      render: (isUsed: boolean) => (
        <Tag color={isUsed ? 'red' : 'green'}>
          {isUsed ? '已使用' : '未使用'}
        </Tag>
      ),
    },
    {
      title: '创建者',
      dataIndex: 'created_by_username',
      key: 'created_by_username',
      width: 120,
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      width: 180,
      render: (time: string) => formatDateTime(time),
    },
    {
      title: '使用者',
      dataIndex: 'used_by_username',
      key: 'used_by_username',
      width: 120,
      render: (username: string | null) => username || '-',
    },
    {
      title: '使用时间',
      dataIndex: 'used_time',
      key: 'used_time',
      width: 180,
      render: (time: string | null) => time ? formatDateTime(time) : '-',
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_: any, record: InvitationCode) => (
        <Popconfirm
          title="确定要删除这个邀请码吗？"
          onConfirm={() => handleDeleteInvitationCode(record.id)}
          okText="确定"
          cancelText="取消"
          disabled={record.is_used}
        >
          <Button 
            type="link" 
            danger 
            size="small"
            icon={<DeleteOutlined />}
            disabled={record.is_used}
          >
            删除
          </Button>
        </Popconfirm>
      ),
    },
  ];

  return (
    <Card>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Title level={4} style={{ margin: 0 }}>邀请码管理</Title>
        <Space>
          <Button 
            icon={<ReloadOutlined />} 
            onClick={() => loadInvitationCodes()}
            loading={loading}
          >
            刷新
          </Button>
          <Button 
            icon={<DownloadOutlined />} 
            onClick={handleExportInvitationCodes}
            loading={exportLoading}
          >
            导出Excel
          </Button>
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={() => setCreateModalVisible(true)}
          >
            生成邀请码
          </Button>
        </Space>
      </div>

      {/* 筛选区域 */}
      <Row style={{ marginBottom: 16 }}>
        <Col span={6}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <span>使用状态：</span>
            <Select
              value={usageFilter}
              onChange={handleFilterChange}
              style={{ width: 120 }}
              size="small"
            >
              <Select.Option value="all">全部</Select.Option>
              <Select.Option value="unused">未使用</Select.Option>
              <Select.Option value="used">已使用</Select.Option>
            </Select>
          </div>
        </Col>
        <Col span={18} style={{ textAlign: 'right' }}>
          <span style={{ color: '#666', fontSize: '12px' }}>
            共 {filteredInvitationCodes.length} 个邀请码
            {usageFilter !== 'all' && ` (筛选自 ${invitationCodes.length} 个)`}
          </span>
        </Col>
      </Row>

      <Table
        columns={columns}
        dataSource={filteredInvitationCodes}
        rowKey="id"
        loading={loading}
        pagination={{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showSizeChanger: false,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 个邀请码`,
          onChange: handlePageChange,
        }}
        size="small"
      />

      {/* 生成邀请码的模态框 */}
      <Modal
        title="生成邀请码"
        open={createModalVisible}
        onCancel={() => {
          setCreateModalVisible(false);
          form.resetFields();
        }}
        footer={null}
        width={400}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleCreateInvitationCodes}
          initialValues={{ count: 1 }}
        >
          <Form.Item
            name="count"
            label="生成数量"
            rules={[
              { required: true, message: '请输入生成数量' },
              { type: 'number', min: 1, max: 100, message: '数量必须在1-100之间' }
            ]}
          >
            <InputNumber
              min={1}
              max={100}
              style={{ width: '100%' }}
              placeholder="请输入要生成的邀请码数量"
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                生成
              </Button>
              <Button onClick={() => {
                setCreateModalVisible(false);
                form.resetFields();
              }}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
};

export default InvitationCodeManagement;
